<!-- 加速域名 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset" />
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row :gutter="20" v-if="tab">
        <el-tabs type="border-card" v-if="tab" style="margin-top: 16px" @tab-click="tabClick">
          <el-tab-pane label="日期趋势" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :chartData="barchartData" @barclick="echartsClick" title="日期趋势" />
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="用户分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart :title="'用户分析'" tooltip="加速次数" :chartData="pie1Data" @pieclick="echartsClick" />
              </el-col>
            </el-row>
          </el-tab-pane>
          <!-- <el-tab-pane label="按域名统计" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :title="'按域名统计'" tooltip="加速次数" :chartData="pie2Data"  @pieclick="echartsClick"/>
            </el-col>
          </el-tab-pane> -->
          <el-tab-pane label="域名分类" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :title="'域名分类'" tooltip="加速次数" :chartData="pie3Data" @pieclick="echartsClick" />
            </el-col>
          </el-tab-pane>
          <!-- <el-tab-pane label="按域名小分类统计" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :title="'按域名小分类统计'" tooltip="加速次数" :chartData="pie4Data"  @pieclick="echartsClick"/>
            </el-col>
          </el-tab-pane> -->
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }"
        style="padding-right: 8px; margin: 16px 0">
        <el-table stripe :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号" width="60" type="index" :index="(index) => {
              return index + 1 + (this.pageNum - 1) * this.pageSize;
            }
            ">
          </el-table-column>
          <el-table-column label="首次加速时间" prop="TransTime" align="left" width="160px"></el-table-column>
          <!-- <el-table-column label="访问终端" prop="Name" align="left" width="160px"></el-table-column> -->
          <el-table-column label="首次访问ip" prop="Ip" align="left" width="160px"></el-table-column>
          <el-table-column label="域名" prop="URL" show-overflow-tooltip align="left" width="230px"></el-table-column>
          <el-table-column label="域名分类" prop="Class" show-overflow-tooltip align="left">
            <template slot-scope="{ row }">
              {{ row.Class ? row.Class : "未分类" }}
            </template>
          </el-table-column>
          <el-table-column label="二级分类" prop="SubClass" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="注册地址" prop="RegAddr" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="注册国家" prop="Country" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="注册国家编码" prop="Code" show-overflow-tooltip align="left" width="120px"></el-table-column>
          <el-table-column label="描述备注" prop="Descp" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="安全检测" prop="Security" show-overflow-tooltip align="left"></el-table-column>
          <!-- <el-table-column label="标题" prop="Title" show-overflow-tooltip align="left" ></el-table-column> -->
          <!-- <el-table-column label="位置" prop="Area" show-overflow-tooltip align="left" ></el-table-column> -->
          <el-table-column label="访问次数" prop="ProxyCount" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="处理状态" prop="IsRead" show-overflow-tooltip align="left">
            <template slot-scope="{ row }">
              {{ row.IsRead === 0 ? "未读" : "已读" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="340px">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="openUrlDialog(scope.row, 'release')">加入放行</el-button>
              <el-button size="mini" type="danger" @click="openUrlDialog(scope.row, 'blocking')">加入阻断</el-button>
              <el-button size="mini" type="success" :disabled="scope.row.IsRead !== 0"
                @click="handleEdit(scope.row)">已读</el-button>
              <el-button size="mini" type="primary" @click="handleOpen(scope.row)">打开</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
          :page-size="pageSize" background layout="total, prev, pager, sizes, next, jumper" :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog title="添加域名" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="dialogVisible"
      v-el-drag-dialog width="calc(21% - 13px)">
      <div class="Dialog-title" style="margin-bottom: 10px">请输入域名:</div>
      <el-input v-model="omainName" :maxlength="500"></el-input>
      <!--底部分割线 -->
      <el-divider class="lineToFooter"></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUrl()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import { getNowDay, parseTime, getTreeData, ParamDictURLtype, Maintype } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
export default {
  components: { connsearch, piechart, barchart },
  directives: { elDragDialog },
  data() {
    let that = this;
    return {
      tabTitle: "日期趋势",
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      searchform: {},
      barchartData: { xAxis: [], series: [] },
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      Options: [],
      searchobj: {},
      dialogVisible: false,
      omainName: "",
      formOptions: [
        {
          col: 8,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val;
            }
          }
        },
        {
          col: 8,
          label: "域名",
          prop: "URL",
          element: "el-input",
          placeholder: "请输入域名,支持模糊查询。",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.URL = val;
            }
          }
        },
        {
          col: 8,
          label: "域名分类",
          prop: "type",
          element: "el-select",
          initValue: "",
          placeholder: "请选择域名分类",
          options: [
            { label: "全部", value: "" },
            { label: "破坏性类", value: "破坏性类" },
            { label: "成人类", value: "成人类" },
            { label: "商业类", value: "商业类" },
            { label: "信息技术类", value: "信息技术类" },
            { label: "休闲娱乐类", value: "休闲娱乐类" },
            { label: "知识类", value: "知识类" },
            { label: "政府类", value: "政府类" },
            { label: "非营利类", value: "非营利类" },
            { label: "恶意网站类", value: "恶意网站类" },
            { label: "个人类", value: "个人类" },
            { label: "其他类", value: "其他类" },
            { label: "未分类", value: "未分类" },
          ],
          events: {
            input(val) {
              that.searchform.type = val;
            }
          }
        },
        {
          col: 8,
          label: "处理状态",
          prop: "IsRead",
          element: "el-select",
          initValue: 0,
          placeholder: "请选择处理状态",
          options: [
            { label: "全部", value: 0 },
            { label: "未读", value: 1 },
            { label: "已读", value: 2 }
          ],
          events: {
            input(val) {
              that.searchform.IsRead = val;
            }
          }
        },
        // {
        //   col: 8,
        //   label: "审计结果",
        //   prop:"Status",
        //   element: "el-select",
        //   initValue: 0,
        //   placeholder: "请选择审计结果",
        //   options:[
        //     { label: '全部', value: 0},
        //     { label: '阻断', value: 1},
        //     { label: '直通', value: 2},
        //     { label: '加速', value: 3},
        //   ],
        //   events: {
        //     input(val) {
        //       that.searchform.Status = val
        //     },
        //   },
        // },
        {
          col: 8,
          label: "访问次数超过",
          prop: "Count",
          element: "el-input",
          initValue: 0,
          maxlength: 10,
          placeholder: "请输入访问次数，0表示不限制",
          events: {
            input(val) {
              that.searchform.Count = val;
            }
          }
        }
      ]
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get("DefaultPageLength") * 1;
    let xTime = new Date().getTime();
    let endTime = new Date(new Date().setHours(0, 0, 0, 0));
    let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
    // let arr = [ parseTime(startTime), parseTime(xTime)]
    let arr = [parseTime(startTime), ""];
    this.formOptions.map((item) => {
      if (item.label === "日期") {
        item.initValue = arr;
      }
    });
    this.$set(this.searchform, "timeRange", arr);
    this.getData();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() { },
  methods: {
    getData() {
      this.GetHistoryProxyLog();
      switch (this.tabTitle) {
        case "用户分析":
          this.GetHistoryProxySumByIp();
          break;
        case "日期趋势":
          this.GetHistoryProxyURLSumGroupByDate();
          break;
        case "域名分类":
          this.GetHistoryProxySumByMainClass();
          break;
        default:
          this.GetHistoryProxySumBySubClass();
          break;
      }
    },
    async openUrlDialog(row, operationType) {
      this.operationType = operationType;
      this.omainName = row.URL;
      const res = await connrequest(operationType === "blocking" ? "GetForbiddenURL" : "GetV2rayURL");
      let UrlList = [];
      res.Data = res.Data || [];
      res.Data.map((item) => {
        UrlList.push({ url: item });
      });
      this.UrlList = UrlList;
      this.dialogVisible = true;
    },
    async submitUrl() {
      if (!this.omainName) {
        this.$message.error("域名不能为空");
        return false;
      }
      if (this.operationType === "blocking") {
        if (this.UrlList.find((item) => item.url === this.omainName) !== undefined) {
          this.$message.error("该域名已经在阻断名单");
          return false;
        }
        let data = {
          Data: { URL: this.omainName }
        };
        const res = await connrequest("AddForbiddenURL", data);
        if (res.Status.StatusCode === 0) {
          this.$message.success("域名加入阻断成功");
          this.pageNum = 1;
          this.searchobj = {};
          this.getData();
          this.dialogVisible = false;
        }
      } else {
        this.omainName = this.omainName.replace(/^https?\:\/\//i, "");
        if (this.UrlList.find((item) => item.url === this.omainName) !== undefined) {
          this.$message.error("该域名已经在加速名单");
          return false;
        }
        let data = {
          Data: { URL: this.omainName }
        };
        const res = await connrequest("AddV2rayURL", data);
        if (res.Status.StatusCode === 0) {
          this.$message.success("域名加入放行成功");
          this.searchobj = {};
          this.pageNum = 1;
          this.getData();
          this.dialogVisible = false;
        }
      }
    },
    tabClick(row) {
      this.tabTitle = row.label;
      switch (this.tabTitle) {
        case "用户分析":
          this.GetHistoryProxySumByIp();
          break;
        case "日期趋势":
          this.GetHistoryProxyURLSumGroupByDate();
          break;
        case "域名分类":
          this.GetHistoryProxySumByMainClass();
          break;
        default:
          this.GetHistoryProxySumBySubClass();
          break;
      }
    },
    async handleEdit(row) {
      const data = {
        Data: {
          AutoID: row.AutoID
        }
      };
      const res = await connrequest("ConfirmHistoryProxyURL", data);
      if (res.Status.StatusCode === 0) {
        this.$message.success("操作成功");
        await this.GetHistoryProxyLog();
      }
    },
    handleOpen(row) {
      window.open("https://" + row.URL);
    },
    echartsClick(val, title) {
      this.pageNum = 1;
      if (title === "用户分析") {
        this.searchobj = { DeviceIP: val };
        this.GetHistoryProxyLog(this.searchobj);
      } else if (title === "日期趋势") {
        this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` };
        this.GetHistoryProxyLog(this.searchobj);
      } else if (title === "域名分类") {
        this.searchobj = { URLClass: val };
        this.GetHistoryProxyLog(this.searchobj);
      }
    },
    // 获取事件日期统计
    async GetHistoryProxyURLSumGroupByDate() {
      let xAxis = [];
      let series = [];
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          Name: this.searchform.Name || "",
          Descp: this.searchform.Descp || "",
          SumCount: 10
        }
      };
      const res = await connrequest("GetHistoryProxyURLSumGroupByDate", data);
      res.Data = res.Data || [];
      res.Data.map((item) => {
        xAxis.push(item.Name);
        series.push(item.Count);
      });
      this.barchartData = { xAxis, series };
    },
    processData(data) {
      // 1. 提取所有 MainClass
      const allMainClasses = data.map((item) => item.MainClass);

      // 2. 去重（使用 Set）
      const uniqueMainClasses = [...new Set(allMainClasses)];

      // 3. 格式化为 el-select 数据源
      const selectOptions = uniqueMainClasses.map((mainClass) => ({
        label: mainClass,
        value: mainClass
      }));
      return selectOptions;
    },
    treeing(arr) {
      let res = []; // 存放结果集
      let map = {};
      // 判断对象是否有某个属性
      let getHasOwnProperty = (obj, property) => Object.prototype.hasOwnProperty.call(obj, property);
      // 边做map存储，边找对应关系
      for (const i of arr) {
        map[i.SubClass] = {
          ...i,
          children: getHasOwnProperty(map, i.SubClass) ? map[i.SubClass].children : []
        };
        const newItem = map[i.SubClass];
        if (i.MainClass === "根节点") {
          res.push(newItem);
        } else {
          if (!getHasOwnProperty(map, i.MainClass)) {
            map[i.MainClass] = {
              children: []
            };
          }
          map[i.MainClass].children.push(newItem);
        }
      }
      return res;
    },
    // 获取加速用户统计
    async GetHistoryProxySumByIp() {
      let arr;
      if (this.searchform?.type?.length > 0) {
        let subClass = this.searchform?.type[this.searchform?.type?.length - 1];
        arr = this.Options.filter((item) => {
          return item.SubClass === subClass;
        });
      }
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          MainClassID: arr?.length > 0 ? arr[0].MainID : 0,
          ClassID: arr?.length > 0 ? arr[0].ClassID : 0,
          Name: "",
          URL: this.searchform?.URL || "",
          SumCount: 10
        }
      };
      const res = await connrequest("GetHistoryProxySumByIp", data);
      let pie1Data = [];
      res.Data = res.Data || [];
      res.Data.map((item) => {
        pie1Data.push({ name: item.Name, value: item.Count });
      });
      this.pie1Data = pie1Data;
    },
    // 获取域名大类统计
    async GetHistoryProxySumByMainClass() {
      let arr;
      if (this.searchform?.type?.length > 0) {
        let subClass = this.searchform?.type[this.searchform?.type?.length - 1];
        arr = this.Options.filter((item) => {
          return item.SubClass === subClass;
        });
      }
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          MainClassID: arr?.length > 0 ? arr[0].MainID : 0,
          ClassID: arr?.length > 0 ? arr[0].ClassID : 0,
          Name: "",
          URL: this.searchform?.URL || "",
          SumCount: 10
        }
      };
      const res = await connrequest("GetHistoryProxySumByMainClass", data);
      let pie3Data = [];
      res.Data = res.Data || [];
      res.Data.map((item) => {
        pie3Data.push({ name: item.Name, value: item.Count });
      });
      this.pie3Data = pie3Data;
    },
    // 获取域名小类统计
    async GetHistoryProxySumBySubClass() {
      let arr;
      if (this.searchform?.type?.length > 0) {
        let subClass = this.searchform?.type[this.searchform?.type?.length - 1];
        arr = this.Options.filter((item) => {
          return item.SubClass === subClass;
        });
      }
      const data = {
        Filter: {
          MainClassID: arr?.length > 0 ? arr[0].MainID : 0,
          ClassID: arr?.length > 0 ? arr[0].ClassID : 0,
          Name: "",
          URL: this.searchform?.URL || "",
          SumCount: 10
        }
      };
      const res = await connrequest("GetHistoryProxySumBySubClass", data);
      let pie4Data = [];
      res.Data = res.Data || [];
      res.Data.map((item) => {
        pie4Data.push({ name: ParamDictURLtype(item.ClassID), value: item.Count });
      });
      this.pie4Data = pie4Data;
    },
    // 获取域名加速日志
    async GetHistoryProxyLog(searchobj = {}) {
      let arr;
      if (this.searchform?.type?.length > 0) {
        let subClass = this.searchform?.type[this.searchform?.type?.length - 1];
        arr = this.Options.filter((item) => {
          return item.SubClass === subClass;
        });
      }
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          MainClassID: arr?.length > 0 ? arr[0].MainID : 0,
          ClassID: arr?.length > 0 ? arr[0].ClassID : 0,
          URL: this.searchform?.URL || "",
          Name: this.searchform?.Name || "",
          IsRead: this.searchform?.IsRead || 0,
          Count: this.searchform?.Count * 1 || 0,
          Status: this.searchform?.Status || 0,
          URLClass: this.searchform?.type === "全部" || !this.searchform?.type ? "" : this.searchform?.type,
          ...searchobj
        }
      };
      const res = await connrequest("GetHistoryProxyLog", data);
      res.Data = res.Data || [];
      res.Data.map((item) => {
        item.ClassID = ParamDictURLtype(item.ClassID);
        item.TransTime = parseTime(item.TransTime, "{y}-{m}-{d} {h}:{i}:{s}");
        return item;
      });
      this.tableData = res.Data;
      this.total = res.Paging.TotalCount;
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1;
      this.GetHistoryProxyLog(this.searchobj);
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.GetHistoryProxyLog(this.searchobj);
    },
    handleClick() {
      this.tab = !this.tab;
    },
    search(val) {
      this.pageNum = 1;
      this.searchform = { ...val };
      if (this.searchform.timeRange) {
        this.searchobj = {
          StartTime: this.searchform?.timeRange[0] || "",
          EndTime: this.searchform?.timeRange[1] || ""
        };
      }
      this.getData();
    },
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0));
      let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
      let arr = [parseTime(startTime), ""];
      this.pageNum = 1;
      this.formOptions = this.formOptions.map((item) => {
        if (item.label === "日期") {
          item.initValue = arr;
        } else if (item.label === "域名分类") {
          item.initValue = "";
        } else if (item.label === "处理状态" || item.label === "审计结果" || item.label === "访问次数超过") {
          item.initValue = 0;
        } else {
          item.initValue = "";
        }
        return item;
      });
      this.searchform = {};
      this.searchobj = {};
      this.$set(this.searchform, "timeRange", arr);
      this.$set(this.searchform, "IsRead", 0);
      this.$set(this.searchform, "Status", 0);
      this.$set(this.searchform, "Count", 0);
      this.$refs.connsearch.addInitValue();
      this.getData();
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";
</style>
